package cn.jobstart.common.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;

import cn.jobstart.common.StringUtil;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author sunke
 * @version 1.0
 * @Description
 * @date 2023-01-16 16:36
 */
public class EasyPoiUtil {


    public static void excelResponse(HttpServletResponse response, List dataList, Class head) throws Exception {
        excelResponse(new ExportParams(), response, dataList, head);
    }


    public static void excelResponse(String sheetName, HttpServletResponse response, List dataList, Class head) throws Exception {

        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(sheetName);
        excelResponse(new ExportParams(), response, dataList, head);
    }

    public static void excelResponse(ExportParams exportParams, HttpServletResponse response, List dataList, Class head) throws Exception {

        if (StringUtil.isNullOrEmpty(exportParams)) {
            exportParams = new ExportParams();
        }


        String excelFileName=exportParams.getSheetName();

//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
  //      response.setHeader("Content-disposition", "attachment; filename=" + excelFileName+".xlsx");


        response.setHeader("content-disposition","attachment;filename*=UTF-8''" + URLEncoder.encode(excelFileName,"UTF-8")+".xlsx"); //解决中文乱码

        response.setContentType("application/x-download"); //跳出窗口下载

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,
                head, dataList);


        OutputStream outputStream = response.getOutputStream();

        workbook.write(outputStream);


        try {
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
